package h_Executor;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.commons.lang3.time.StopWatch;

public class Executor_demo2 {

	/**
	 * 上面的程序随机生成了100000个随机数，然后统计这些数字中每个数字10进制中具有多少个数位3的数量和。
	 * 使用具有10个线程的线程池进行计算，最终通过Future引用对象的结果来统计答案。
	 * @param args
	 */
	public static void main(String[] args) {
		Random random = new Random();
		List<Integer> numbers = new ArrayList<>();
		for (int i = 0; i < 100000; i++) {
			numbers.add(random.nextInt(100000));
		}
		StopWatch sw=new StopWatch();
		long time1 = System.currentTimeMillis();
		sw.start();
		int result = calculate(numbers,3);
		sw.stop();
		long time2 = System.currentTimeMillis()-time1;
		System.out.println(result+"多线程耗时:"+sw.getTime());
		System.out.println(result+"多线程耗时:"+time2);
		
		
	}


	private static int calculate(List<Integer> numbers, int digit) {
		List<Callable<Integer>> tasks = new ArrayList<>();
		for (Integer x : numbers) {
			tasks.add(() -> {
				int count= 0;
				int y=x;
				do {
					if (y%10 == digit) {
						count++;
					}
					y/=10;
				} while (y > 0);
				return count;
			});
		}
		//具有10个线程的线程池
		ExecutorService service = Executors.newFixedThreadPool(10);
		int answer = 0;
		try {
			List<Future<Integer>> results=service.invokeAll(tasks);
			for (Future<Integer> result : results) {
				answer+=result.get();
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		return answer;
	}
	
	
}
